// search.js
Page({
    data: {
        keyword: '',
        showSuggestion: false,
        showResult: false,
        isFocused: true,
        suggestionList: [],
        searchResult: [],
        historyList: [],

        // 美化热门标签的颜色
        tagColors: [
            '#ff7a7c', '#7b61ff', '#00c6ff', '#ff976a',
            '#ff6b9d', '#c273e6', '#00d2d3', '#ffc367'
        ],

        hotTags: ['平板', '热销爆款', '限时优惠', '家居生活', '数码电子', '时尚服饰'],

        // 模拟商品数据库
        products: [
            { id: 1, title: '2023新款夏季连衣裙女装时尚显瘦气质碎花长裙', price: 199.9, image: '/assets/images/my/avatar.jpg', tags: ['新品', '女装', '连衣裙'] },
            { id: 2, title: 'Apple iPhone 14 Pro 256GB 暗紫色 移动联通电信5G手机', price: 7999, image: '/assets/images/my/avatar.jpg', tags: ['手机', '苹果', '5G'] },
            { id: 3, title: '小米空气净化器4 Pro 家用除甲醛除菌除异味智能互联', price: 1299, image: '/assets/images/my/avatar.jpg', tags: ['家电', '小米', '净化器'] },
            { id: 4, title: '耐克官方AIR MAX 270 React 男子运动鞋气垫鞋', price: 899, image: '/assets/images/my/avatar.jpg', tags: ['运动鞋', '耐克', '男鞋'] },
            { id: 5, title: '华为平板MatePad 11 2023款 11英寸 二合一平板电脑', price: 2599, image: '/assets/images/my/avatar.jpg', tags: ['平板', '华为', '二合一'] },
            { id: 6, title: '苏泊尔电饭煲家用智能预约5L大容量煮饭锅', price: 399, image: '/assets/images/my/avatar.jpg', tags: ['厨具', '苏泊尔', '电饭煲'] },
            { id: 7, title: '三星 Galaxy S23 Ultra 12GB+256GB 幻影黑 5G手机', price: 7699, image: '/assets/images/my/avatar.jpg', tags: ['手机', '三星', '5G'] },
            { id: 8, title: '大疆 DJI Mini 3 Pro 无人机 畅飞套装', price: 4788, image: '/assets/images/my/avatar.jpg', tags: ['数码', '无人机', '大疆'] }
        ]
    },

    onLoad(options) {
        const history = wx.getStorageSync('searchHistory') || [];
        this.setData({
            historyList: history
        });
    },

    // 输入框内容变化时触发
    onInput(e) {
        const value = e.detail.value.trim();
        this.setData({
            keyword: value
        });

        // 如果输入为空，清空联想和结果
        if (value === '') {
            this.setData({
                showSuggestion: false,
                showResult: false,
                suggestionList: []
            });
            return;
        }

        // 从商品数据库中实时联想结果
        const suggestions = this.data.products.filter(product =>
            product.title.toLowerCase().includes(value.toLowerCase()) ||
            product.tags.some(tag => tag.toLowerCase().includes(value.toLowerCase()))
        );

        this.setData({
            suggestionList: suggestions,
            showSuggestion: true,  // 显示联想列表
            showResult: false      // 隐藏搜索结果
        });
    },

    // 输入框聚焦时触发
    onFocus() {
        // 如果已有输入内容，显示联想
        if (this.data.keyword) {
            this.onInput({ detail: { value: this.data.keyword } });
        }
    },

    // 点击"搜索"按钮时触发
    onSearch() {
        const { keyword } = this.data;
        if (keyword.trim()) {
            this.doSearch(keyword.trim());
        } else {
            // 可以给用户一个提示，比如toast
            wx.showToast({
                title: '请输入搜索关键词',
                icon: 'none'
            });
        }
    },

    // 按回车键时触发
    onConfirm(e) {
        const value = e.detail.value.trim();
        if (value) {
            this.doSearch(value);
        }
    },

    // 选择联想列表中的一项
    selectSuggestion(e) {
        const { title } = e.currentTarget.dataset.item;
        this.setData({
            keyword: title,
            showSuggestion: false
        });
        this.doSearch(title);
    },

    // 执行搜索的核心逻辑
    doSearch(keyword) {
        this.addToHistory(keyword);

        wx.showLoading({
            title: '搜索中...'
        });

        // 使用setTimeout模拟网络请求
        setTimeout(() => {
            const result = this.data.products.filter(product =>
                product.title.toLowerCase().includes(keyword.toLowerCase()) ||
                product.tags.some(tag => tag.toLowerCase().includes(keyword.toLowerCase()))
            );

            this.setData({
                searchResult: result,
                showResult: true,      // 显示搜索结果
                showSuggestion: false  // 隐藏联想列表
            });

            wx.hideLoading();
        }, 500);
    },

    // ---- 历史记录相关方法 ----
    searchHistory(e) {
        const keyword = e.currentTarget.dataset.keyword;
        this.setData({ keyword });
        this.doSearch(keyword);
    },

    searchHotTag(e) {
        const keyword = e.currentTarget.dataset.tag;
        this.setData({ keyword });
        this.doSearch(keyword);
    },

    addToHistory(keyword) {
        let history = this.data.historyList;
        const index = history.indexOf(keyword);
        if (index !== -1) history.splice(index, 1);
        history.unshift(keyword);
        if (history.length > 10) history = history.slice(0, 10);
        wx.setStorageSync('searchHistory', history);
        this.setData({ historyList: history });
    },

    clearHistory() {
        wx.showModal({
            title: '提示',
            content: '确定要清空所有搜索历史吗？',
            success: (res) => {
                if (res.confirm) {
                    wx.removeStorageSync('searchHistory');
                    this.setData({ historyList: [] });
                }
            }
        });
    }
});